/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */
package com.tengtong.duang.commons.convert.support;

import com.tengtong.duang.commons.collections.ArrayUtils;
import com.tengtong.duang.commons.convert.ConditionalConverter;
import com.tengtong.duang.commons.convert.ConversionService;

/**
 * 将字符串转换成字符串数组
 * 
 * @author mling
 *
 */
public class StringToArrayConverter implements ConditionalConverter{

	private final ConversionService helperConverter;
	
	public StringToArrayConverter(ConversionService helperConverter){
		this.helperConverter = helperConverter;
	}
	
	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#convert(java.lang.Object, java.lang.Class)
	 */
	@Override
	public Object convert(Object source, Class targetType){
		if(source == null){
			return null;
		}
		Class<?> componentType = targetType.getComponentType();
		if(componentType != null && String.class.equals(componentType)){
			return new String[]{source.toString()};
		}else{
			if(componentType != null){
				Object[] obs = ArrayUtils.newSimpleArray(targetType, 1);
				obs[0] = helperConverter.convert(source, componentType);
				
				return obs;
			}
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#matches(java.lang.Class, java.lang.Class)
	 */
	@Override
	public boolean matches(Class<?> sourceType, Class<?> targetType) {
		return targetType.isArray() && String.class.equals(sourceType);
	}

}
